CREATE PROCEDURE spu_Com_Trae_CtaCtes_Pedido
 @cCodEmp  varchar(02),              
 @cAnio   Varchar(04),        
 @cTipoAnal  varchar(02),        
 @cArticulo Varchar(20),        
 @Flag  Varchar(1)        
 AS         
 DECLARE @xArticulo Varchar(20)        
 SET NOCOUNT ON  
          
 IF @Flag='I'        
    Select TOP 2 Co04CodPro,ccm02nom,ccm02Correo,Co04Articu,CO04PRECIO,CO04FECDOC,CO04DSCT1,CO04DSCT2        
   From ccm02cta ,co04movi            
   Where        
   ccm02emp  =  @cCodEmp            
   And ccm02tipana =  @cTipoAnal           
   And CO04CODEMP =  ccm02emp        
   And CO04AA =  @cAnio        
   And Co04CodPro  =  ccm02cod        
   And Co04Articu  =  @cArticulo        
   GROUP BY Co04CodPro,ccm02nom,ccm02Correo,Co04Articu,CO04PRECIO,CO04FECDOC,CO04DSCT1,CO04DSCT2           
   ORDER BY CO04FECDOC,Co04CodPro,ccm02nom,ccm02Correo,Co04Articu,CO04PRECIO,CO04DSCT1,CO04DSCT2   DESC        
 ELSE IF @Flag='L'        
     BEGIN          
   CREATE TABLE #Tempo(Co04CodPro Varchar(20),        
         ccm02nom Varchar(100),        
         ccm02Correo Varchar(100),        
         Co04Articu Varchar(20),        
         Co04Precio Float,        
         Co04FecDoc  Datetime,    
  CO04DSCT1   Float,    
  CO04DSCT2   Float)         
          
   DECLARE Articulos CURSOR FOR SELECT ccb01valor FROM ccb01rngimp        
          WHERE ccb01pro  = 'PROVEE'        
          AND ccb01emp    = @cCodEmp          
          AND ccb01usu    = @cArticulo        
   OPEN Articulos        
        
  FETCH Articulos INTO @xArticulo        
          
  IF @@FETCH_STATUS = 0        
     BEGIN        
     WHILE @@FETCH_STATUS = 0        
    BEGIN        
     INSERT INTO #Tempo        
     SELECT TOP 2 Co04CodPro,ccm02nom,ccm02Correo,Co04Articu,Co04Precio,Co04FecDoc,CO04DSCT1,CO04DSCT2               
     FROM ccm02cta ,co04movi            
     WHERE        
     ccm02emp  =  @cCodEmp            
     And ccm02tipana =  @cTipoAnal           
     And CO04CODEMP =  ccm02emp        
     And CO04AA =  @cAnio        
     And Co04CodPro  =  ccm02cod        
     And Co04Articu  =  @xArticulo        
     GROUP BY Co04CodPro,ccm02nom,ccm02Correo,Co04Articu,CO04PRECIO,CO04FECDOC,CO04DSCT1,CO04DSCT2                
     ORDER BY CO04FECDOC,Co04CodPro,ccm02nom,ccm02Correo,Co04Articu,CO04PRECIO,CO04DSCT1,CO04DSCT2  DESC        
           
       FETCH Articulos INTO @xArticulo        
   END        
                  
     END         
  CLOSE Articulos        
  DEALLOCATE Articulos        
        
       SELECT Co04CodPro,ccm02nom,ccm02Correo,Co04Precio,CO04DSCT1,CO04DSCT2 From #Tempo        
          GROUP BY Co04CodPro,ccm02nom,ccm02Correo,Co04Precio,CO04DSCT1,CO04DSCT2    
         ORDER BY Co04CodPro,ccm02nom,ccm02Correo,Co04Precio,CO04DSCT1,CO04DSCT2      
            
       DROP TABLE #Tempo        
 END            
